/*
  Copyright (c) 2010 Les Newell. All rights reserved

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

#include "wx_pch.h"
#include <vector>
#include "ModuleData.h"

bool ModuleData::Refresh(Serial * source)
{
    wxCHECK_MSG(source,false,_T("No source"));
    Module mod;
    Signal sig;
    bool first = true;
    clear();

    wxArrayString data;
    if (!source->ListModules(data))
    {
        return(false);
    }

    for (int ct=0; ct<data.Count(); ct++)
    {
        wxString st = data[ct];
        if (st.IsEmpty())
        {
            continue;
        }
        if (st.Left(2) == _T("  ")) //a parameter
        {
            wxStringTokenizer tok(st.Mid(2),_T(" "));
            sig.name = tok.GetNextToken();
            sig.canWrite = (tok.GetNextToken() == _T("W"));
            sig.isInt = (tok.GetNextToken().Right(1) != _T("F"));
            sig.id = tok.GetNextToken();
            mod.signals.push_back(sig);
        }
        else
        {
            if (!first)
            {
                push_back(mod);
            }
            first = false;
            mod.name = st;
            mod.signals.clear();
        }
    }
    if (!first)
    {
        push_back(mod);
    }
    return(true);
}

void ModuleData::ListModules(wxControlWithItems * target)
{
    target->Clear();
    for (int ct=0; ct< size(); ct++)
    {
        target->Append(operator[](ct).name);
    }
}

bool ModuleData::Save(const wxString& fileName, Serial * serial)
{
    wxFFile fil(fileName,_T("w"));
    if (!fil.IsOpened())
    {
        return(false);
    }
    for (int ct=0; ct< size(); ct++)
    {
        Module& mod = at(ct);
        for (int s=0; s < mod.signals.size(); s++)
        {
            Signal& sig = mod.signals[s];
            if (!sig.canWrite)
            {
                continue;
            }
            if (!serial->GetValue(sig.name, sig.value))
            {
                return(false);
            }
            wxString txt = sig.name + _T('=') + sig.ToString() + _T('\n');
            fil.Write(txt);
        }
    }
    return(true);
}


